<template>
  <div
  v-loading="loading"
  element-loading-text="拼命加载中"
  id="mainBox"
  >
    <el-upload
      class="upload-demo"
      action="http://sugao.fun:8090/file/fileUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      accept=".rar,.zip"
      :headers="headerObj"
      :on-success="uploadSuccess"
      :on-exceed="handleExceed"
      :show-file-list="false"
      :file-list="fileList">
          <el-button  type="warning">选择文件</el-button>
      <div slot="tip" class="el-upload__tip">只能上传zip/rar文件，且不超过500kb</div>
    </el-upload>

  <el-table
        :data="tableFileData"
        :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        style="width: 100%;margin-top: 20px;"
        height=90%
        >
        <el-table-column
          prop="filename"
          label="文件名"
         >
        </el-table-column>
        <el-table-column
          prop="filesize"
          label="大小"
          >
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          :formatter="statusForma"
          >
        </el-table-column>
        <el-table-column
          label="操作">
           <template slot-scope="scope">
                  <el-button
                    @click="deleteRow(scope.$index)"
                    type="danger"
                    size="small">
                    移除
                  </el-button>
                </template>
        </el-table-column>
      </el-table>
      <div id="SubmitButton">
        <el-button
        type="primary"
        @click="tempFile"
        >暂存
        </el-button>
        <el-button
        type="success"
        @click="submitFile"
        >提交</el-button>
      </div>
  </div>
</template>

<script>
  export default {
created() {
this.proId=this.$route.query.proId
this.phaseId=this.$route.query.phaseId
this.getPfData()
},
data() {
  return {
    loading:true,
    proId:'',
    phaseId:'',
    headerObj: {
    	token: this.$store.state.token,
    	tokenHead: this.$store.state.tokenHead,
    	jsession_id: this.$store.state.jsession_id
    },
    //{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
    fileList: [],
    tableFileData: [],
    addFile:[],
    deleFile:[],
    fileInfo:{
      filename:'',
      filesize:'',
      status:'',
      pfPath:''
    }
  }
},
methods: {
  statusForma(row){
    console.log(row)
    if(row.status==undefined){
      return "已上传"
    }else{
      return "未上传"
    }
  },
    getPfData(){
      this.$api.phase.getPhaseFileByPhaseId({phaseId:this.phaseId}).then((res)=>{
        this.tableFileData=res.data.data
        console.log(res)
        this.loading=false
      })
    },
    addFileAxios(){
      console.log("addFileAxios")
       this.tableFileData.forEach(item=>{
         if(item.pfId==undefined){
           this.addFile.push(JSON.parse(JSON.stringify(item)))
         }
       })
       console.log(this.addFile)
       this.$api.phase.addPhaseFiles({
         phaseFileInfo:JSON.stringify(this.addFile),
         phaseId:this.phaseId,
         proId:this.proId
       }).then((res)=>{
         console.log(res)
       })
    },
    deleFileAxios(){
      console.log("deleFileAxios")
      for(let i = 0 ; i<this.deleFile.length;i++){
        this.$api.phase.deletePhaseFile({pfId:this.deleFile[i].pfId}).then((res)=>{
          console.log(res)
        })
      }

    },
    tempFile(){
      this.addFileAxios()
      this.deleFileAxios()
      setTimeout(()=>{
        this.getPfData()
      },1000)
      this.$message({
        type: 'success',
        center:true,
        message: '暂存成功!',
        duration:2000,
        offset:screen.height/2 -200
      });
    },
    submitFile(){

      this.addFileAxios()
      this.deleFileAxios()
      this.$confirm('此操作将提交文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {

        this.$message({
          type: 'success',
          center:true,
          message: '提交成功!',
          duration:2000,
          offset:screen.height/2 -200
        });
        this.$router.push({path:'/myProject'})
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交',
          center:true,
          duration:2000,
          offset:screen.height/2 -200
        });
      });
    },
    deleteRow(index){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        if(this.tableFileData[index].pfId!=undefined){
          this.deleFile.push(JSON.parse(JSON.stringify(this.tableFileData[index])))
        }
        this.tableFileData.splice(index,1)
        this.$message({
          type: 'success',
          center:true,
          message: '删除成功!',
          duration:2000,
          offset:screen.height/2 -200
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //字节B转化成KB，MB，GB
    change(limit){
        var size = "";
        if(limit < 0.1 * 1024){                            //小于0.1KB，则转化成B
            size = limit.toFixed(2) + "B"
        }else if(limit < 0.1 * 1024 * 1024){            //小于0.1MB，则转化成KB
            size = (limit/1024).toFixed(2) + "KB"
        }else if(limit < 0.1 * 1024 * 1024 * 1024){        //小于0.1GB，则转化成MB
            size = (limit/(1024 * 1024)).toFixed(2) + "MB"
        }else{                                            //其他转化成GB
            size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB"
        }

        var sizeStr = size + "";                        //转成字符串
        var index = sizeStr.indexOf(".");                    //获取小数点处的索引
        var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
        if(dou == "00"){                                //判断后两位是否为00，如果是则删除00
            return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
        }
        return size;
    },
    uploadSuccess(res,file){
      this.fileInfo.filename=res.data[0].fileName
      this.fileInfo.pfPath=res.data[0].filePath
      this.fileInfo.filesize=this.change(file.size)
      this.fileInfo.status="未上传"
      this.tableFileData.push(JSON.parse(JSON.stringify(this.fileInfo)))
      console.log(this.tableFileData)
    },
    test(){
      console.log("1")
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    }
  }
      }
</script>

<style scoped>
  #mainBox{
    padding:0 40px;
    height:80%;
  }
  #SubmitButton{
    margin-top: 40px;
    position: absolute;
    left: 50%;
  }

</style>
